package com.xywh.wanandroid.compose_ui.main.bottomBar

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.xywh.composeLibrary.ext.ListFloatingActionButton
import com.xywh.composeLibrary.statex.StateCompose
import com.xywh.wanandroid.compose_ui.main.ArticleItem
import com.xywh.wanandroid.compose_ui.main.cancelOrAddCollectArticle
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.data.model.bean.WXChapterItem
import com.xywh.wanandroid.viewmodel.MainComposeViewModel

@Composable
fun WechatScreen(
    mainComposeViewModel: MainComposeViewModel,
    innerPadding: PaddingValues,
    navigateWebView: (String, String) -> Unit
) {

    val wxChapters =
        mainComposeViewModel.wxChapters.collectAsLazyPagingItems()

    StateCompose(wxChapters) {


        val wechatArticles =
            mainComposeViewModel.wechatArticle.value?.collectAsLazyPagingItems()

        mainComposeViewModel.collectWechatArticleLiveData.collectAsState(initial = "")

        wxChapters[0]?.let {

            if (mainComposeViewModel.wxChapterId == 0) {
                mainComposeViewModel.wxChapterId = it.id
                mainComposeViewModel.getWechatArticle()
            }
        }

        WechatContent(
            innerPadding,
            wxChapters,
            wechatArticles,
            favoriteOnClick = { id, collect ->
                cancelOrAddCollectArticle(collect, mainComposeViewModel, id)
            },
            navigateWebView = navigateWebView
        ) {
            mainComposeViewModel.wxChapterId = it
            mainComposeViewModel.getWechatArticle()
        }
    }
}

@Composable
@OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class)
fun WechatContent(
    innerPadding: PaddingValues,
    wxChapters: LazyPagingItems<WXChapterItem>,
    wechatArticles: LazyPagingItems<ArticleItem>?,
    navigateWebView: (String, String) -> Unit,
    favoriteOnClick: (Int, Boolean) -> Unit,
    tabOnclick: (Int) -> Unit
) {

    val refresh by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(refresh, {
        wechatArticles?.refresh()
    })

    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {

        var state by rememberSaveable { mutableStateOf(0) }
        val listState = rememberLazyListState()

        Column(Modifier.fillMaxSize()) {

            wxChapters.let {
                if (it.itemCount > 0) {
                    SecondaryScrollableTabRow(
                        modifier = Modifier
//                                .padding(top = innerPadding.calculateTopPadding())
                            .fillMaxWidth(),
                        selectedTabIndex = state,
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White,
                        edgePadding = 0.dp,
                        divider = { HorizontalDivider(color = Color.Transparent) },
                        indicator = { tabPositions ->
                            TabRowDefaults.SecondaryIndicator(
                                Modifier.tabIndicatorOffset(tabPositions[state]),
                                color = Color.White
                            )
                        }
                    ) {

                        it.itemSnapshotList.forEachIndexed { index, wxChapter ->
                            Tab(
                                selected = state == index,
                                onClick = {
                                    state = index
                                    if (wxChapter != null) {
                                        tabOnclick.invoke(wxChapter.id)
                                    }
                                },
                                text = {

                                    val fontWeight = if (state == index) {
                                        FontWeight.Bold
                                    } else {
                                        FontWeight.Normal
                                    }
                                    if (wxChapter != null) {
                                        Text(wxChapter.name, fontWeight = fontWeight)
                                    }

                                }
                            )
                        }
                    }
                }

            }

            LazyColumn(
                state = listState,
                // consume insets as scaffold doesn't do it by default
                modifier = Modifier
                    .consumeWindowInsets(innerPadding),
//            contentPadding = innerPadding,
            ) {

                wechatArticles?.let {
                    items(
                        count = wechatArticles.itemCount,
                        key = { index ->
                            val article = wechatArticles[index]
                            "${article?.id ?: ""}${index}"
                        }) {
                        val itemData = wechatArticles[it] ?: return@items
                        ArticleItem(
                            itemData,
                            false,
                            favoriteOnClick = favoriteOnClick
                        ) { title, link ->
                            navigateWebView.invoke(title, link)
                        }

                    }
                }

            }
        }


        Box(
            Modifier
                .padding(10.dp)
                .align(Alignment.BottomEnd)
        ) {
            ListFloatingActionButton(rememberCoroutineScope(), listState)
        }
        PullRefreshIndicator(
            refresh,
            pullRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}
